﻿#include "MainWindow.h"
#include "ui_MainWindow.h"
#include "MainWindow.h"
#include <QGridLayout>
#include "mDlgTest2.h"
#include "stable.h"

#include <QMenuBar>
#include <QToolBar>
#include <QStatusBar>
#include <QDockWidget>
#include <QMessageBox>
#include <QColorDialog>
#include <QFileDialog>
#include <QFontDialog>
#include <QListWidgetItem>
#include <QTreeWidget>
#include <QTableWidget>
#include <QComboBox>
#include <QTimer>
//#include <QtPropertyBrowser>





MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    if(m_Translator.load("mTranslation_zh_CN.qm"))
    {
        qApp->installTranslator(&m_Translator);
        ui->retranslateUi(this);
    }

    ui->m_pLable1->move(0,700);
    ui->m_pLable1->resize(300,50);
    ui->m_pLable1->setText(tr("Practice Event Fileter"));
    ui->m_pLable1->setFont(QFont("新宋体",12));
    ui->m_pLable1->installEventFilter(this);





    //---0定时器
    QTimer* pTimer = new QTimer(this);
    {
        pTimer->start(500);
        connect(pTimer, &QTimer::timeout,
                [=]()
        {
            static int snNumber = 0;
            snNumber > 20 ? snNumber = 0 : 1;
            m_pLabel->setText(tr("Timer:")+ QString::number(snNumber++));
            m_pLabel->setFont(QFont("新宋体",16));
        });
    }



    //---1设置主对话框属性
    {
        this->resize(2000,1300);
        this->move(300,40);
        this->setWindowTitle(tr("Main Dialog"));
//        const char* charStr("主对话框");
//        this->setWindowTitle(QString::fromLocal8Bit(charStr));


        QString str =":/Jpg/Icon.jpg";
        QIcon   TempIcon(str);
        this->setWindowIcon(TempIcon);
        this->setWindowIconText(tr("Cheng Peng"));
    }




    //---2添加菜单栏
    {
        QMenuBar* pMenuBar = ui->menuBar;



        //---2.1添加文件菜单
        {
            QMenu*    pFileMenu       = pMenuBar->addMenu(tr("File"));

            pFileMenu->addAction(tr("Open File"));
            pFileMenu->addSeparator();

            pFileMenu->addAction(tr("Save File"));
            pFileMenu->addSeparator();
        }


        //---2.2添加文件菜单
        {
            QMenu*   pEditMenu       = pMenuBar->addMenu(tr("Edit"));
            pEditMenu->addAction(tr("Copy"));
            pEditMenu->addSeparator();

            pEditMenu->addAction(tr("Cut"));
            pEditMenu->addSeparator();

            pEditMenu->addAction(tr("Past"));
            pEditMenu->addSeparator();
        }
    }



    //---3创建工具栏
    {

        QToolBar* pToolBar =ui->mainToolBar;
        addToolBar(Qt::LeftToolBarArea, pToolBar);
        pToolBar->setAllowedAreas(Qt::LeftToolBarArea | Qt::RightToolBarArea);  //设置停靠位置
        pToolBar->setFloatable(false);                                           //设置是否停靠
        pToolBar->setMovable(true);                                             //设置是否移动


        //---3.1添加工具栏设置
        {
            pToolBar->addAction(tr("Paintor"));
            pToolBar->addSeparator();

            pToolBar->addAction(tr("Icon"));
            pToolBar->addSeparator();
        }


        //---3.2添加工具栏控件
        {
            QSizePolicy TempSizePolicy = this->sizePolicy();
            TempSizePolicy.setHorizontalPolicy(QSizePolicy::Preferred);
            TempSizePolicy.setVerticalPolicy(QSizePolicy::Preferred);



            m_pToolButton1 = new QPushButton(tr("Open modal dialog"),this);
            m_pToolButton1->setSizePolicy(TempSizePolicy);
            pToolBar->addWidget(m_pToolButton1);
            pToolBar->addSeparator();

            m_pToolButton2 = new QPushButton(tr("Open not modal dialog"),this);
            m_pToolButton2->setSizePolicy(TempSizePolicy);
            pToolBar->addWidget(m_pToolButton2);
            pToolBar->addSeparator();

            m_pToolButton3 = new QPushButton(tr("Open color dialog"),this);
            m_pToolButton3->setSizePolicy(TempSizePolicy);
            pToolBar->addWidget(m_pToolButton3);
            pToolBar->addSeparator();

            m_pToolButton4 = new QPushButton(tr("Open file"),this);
            m_pToolButton4->setSizePolicy(TempSizePolicy);
            pToolBar->addWidget(m_pToolButton4);
            pToolBar->addSeparator();

            m_pToolButton5 = new QPushButton(tr("Save file"),this);
            m_pToolButton5->setSizePolicy(TempSizePolicy);
            pToolBar->addWidget(m_pToolButton5);
            pToolBar->addSeparator();

            m_pToolButton6 = new QPushButton(tr("Open font dialog"),this);
            m_pToolButton6->setSizePolicy(TempSizePolicy);
            pToolBar->addWidget(m_pToolButton6);
            pToolBar->addSeparator();
        }

    }



    //---4创建状态栏
    {
        QStatusBar* pStatusBar =ui->statusBar;


        //---状态栏标签控件
        QLabel* pLeftLable   = new QLabel(tr("Left notice information"),this);
        QLabel* pRightLable  = new QLabel(tr("Right notice information"),this);

        pStatusBar->addWidget(pLeftLable);
        pStatusBar->addPermanentWidget(pRightLable);
    }



    //---5创建铆接浮动框
    {
        QDockWidget* pDockWidget = new QDockWidget(tr("Flot box"),this);
        addDockWidget(Qt::TopDockWidgetArea,pDockWidget);
        pDockWidget->setAllowedAreas(Qt::BottomDockWidgetArea | Qt::TopDockWidgetArea);
        pDockWidget->resize(300,300);
    }



    //---6控件练习
    {
        //---6.1创建标签组件
        {
            QSizePolicy TempSizePolicy = this->sizePolicy();
            TempSizePolicy.setHorizontalPolicy(QSizePolicy::Preferred);
            TempSizePolicy.setVerticalPolicy(QSizePolicy::Preferred);



            m_pLabel = new QLabel(tr("Timer:0"),this);
            m_pLabel->move(200,130);
            m_pLabel->resize(300,300);
            m_pLabel->installEventFilter(this);
            m_pLabel->setSizePolicy(TempSizePolicy);



            QPushButton* pButton1 = new QPushButton(this);
            pButton1->setText(tr("close timer"));
            pButton1->move(200,300);
            pButton1->resize(150,50);
            pButton1->setSizePolicy(TempSizePolicy);



            QPushButton* pButton2 = new QPushButton(this);
            pButton2->setText(tr("open timer"));
            pButton2->move(350,300);
            pButton2->resize(150,50);
            pButton2->setEnabled(false);
            pButton2->setSizePolicy(TempSizePolicy);




            connect(pButton1,&QPushButton::clicked,this,
                    [=]()
            {
                pTimer->stop();
                pButton1->setEnabled(false);
                pButton2->setEnabled(true);
            });


            connect(pButton2,&QPushButton::clicked,this,
                    [=]()
            {
                pTimer->start();
                pButton1->setEnabled(true);
                pButton2->setEnabled(false);
            });
        }



        //---6.2创建测试按钮1
        {
            this->m_pTestButton1 = new mTestButton1(this);
            m_pTestButton1->setText(tr("exchange text 1"));
            m_pTestButton1->move(200,100);
            m_pTestButton1->resize(300,50);
            m_pTestButton1->setEnabled(true);



            //---6.2.1连接信号与函数
            void (mTestButton1::*mTestButton1SlotNoPara)() = &mTestButton1::ChangeButtonText;//声明槽函数指针，防止重载
            connect(m_pTestButton1,&mTestButton1::clicked,m_pTestButton1,mTestButton1SlotNoPara);
        }



        //---6.3创建测试按钮2
        {
            m_pChangeLanguageButton = new mTestButton1();
            m_pChangeLanguageButton->setParent(this);
            m_pChangeLanguageButton->setText(tr("set English"));
            m_pChangeLanguageButton->move(200,180);
            m_pChangeLanguageButton->resize(300,50);
            m_pChangeLanguageButton->setEnabled(true);



            //---6.3.1连接信号与函数
            connect(m_pChangeLanguageButton,&mTestButton1::clicked,this,&MainWindow::ChangeLanguageTranslation);
        }


        //---6.4List控件
        {
            QSizePolicy TempSizePolicy = this->sizePolicy();
            TempSizePolicy.setHorizontalPolicy(QSizePolicy::Preferred);
            TempSizePolicy.setVerticalPolicy(QSizePolicy::Preferred);
            QListWidget *pListWidget = new QListWidget(this);
            pListWidget->resize(300,200);
            pListWidget->move(200,400);
            pListWidget->setSizePolicy(TempSizePolicy);


            QListWidgetItem *pListWidgetItem = new QListWidgetItem(tr("title")); // 设置水平头
            pListWidgetItem->setTextAlignment(Qt::AlignCenter);// 设置格式（居中）
            QColor TempColor(255,255,0);
            pListWidgetItem->setBackgroundColor(TempColor);
            pListWidget->addItem(pListWidgetItem);

            QStringList TempStringList;
            TempStringList << tr("123");
            TempStringList << tr("456");
            pListWidget->addItems(TempStringList);
        }


        //---6.5Tree控件
        {
            QTreeWidget *pTreeWidget = new QTreeWidget(this);
            pTreeWidget->resize(600,250);
            pTreeWidget->move(600,100);
            pTreeWidget->setColumnWidth(1,50);
            pTreeWidget->setColumnWidth(2,50);
            pTreeWidget->setColumnWidth(3,50);

            QString strstyleSheet = pTreeWidget->styleSheet();
            strstyleSheet = strstyleSheet
                    + QString("QTreeWidget {border:1px solid rgb(255,0,0); };")

             + QString(" QTreeWidget::branch{  background:rgb(255,0,0);  };");




            pTreeWidget->setStyleSheet(strstyleSheet);



            //---设置标签头
            pTreeWidget->setHeaderLabels(QStringList() << tr("number")<<tr("name")<<tr("sex")<<tr("age")); // 设置水平头


            //---创建根节点1
            {
                QTreeWidgetItem* pItem1 = new QTreeWidgetItem(QStringList() <<"1");
                pTreeWidget->addTopLevelItem(pItem1);


                QStringList TempStringList1;
                TempStringList1<< tr("1.1") << tr("Cheng Peng" )<< tr("man")<<tr("31");
                QTreeWidgetItem*  pSubItem= new QTreeWidgetItem(TempStringList1);
                pSubItem->setBackgroundColor(0,QColor(255,0,0));
                pItem1->addChild(pSubItem);
//                pItem1->setExpanded(true);


                QStringList TempStringList2;
                TempStringList2<< tr("1.2") << tr("Chen Fei") << tr("woman")<<tr("31");
                pSubItem= new QTreeWidgetItem(TempStringList2);
                pSubItem->setBackgroundColor(0,QColor(0,255,255));
                pItem1->addChild(pSubItem);
            }


            //---创建根节点2
            {
                QTreeWidgetItem* pItem2 = new QTreeWidgetItem(QStringList() <<tr("2")<<tr("Xiao Ming")<<tr("man")<<tr("11"));
                pTreeWidget->addTopLevelItem(pItem2);
            }


            //---创建根节点3
            {
                QTreeWidgetItem* pItem3 = new QTreeWidgetItem(QStringList() <<tr("3")<<tr("Xiao Hong")<<tr("woman")<<tr("11"));
                pTreeWidget->addTopLevelItem(pItem3);
            }
        }




        //---6.6Talble控件
        {
            QTableWidget* pTableWidget = new QTableWidget(this);
            pTableWidget->resize(600,250);
            pTableWidget->move(1300,100);
            pTableWidget->setColumnCount(3);    //设置列数
            pTableWidget->setRowCount(5);       //设置行数


            //---设置表头
            pTableWidget->setHorizontalHeaderLabels(QStringList() << tr("name") << tr("sex") << tr("age"));


            //---设置正文
            pTableWidget->setItem(0,0,new QTableWidgetItem());
            QStringList NameList;
            NameList << "a" << "b" << "c" << "d" << "e";

            QStringList SexList;
            SexList << tr("man") << tr("man") << tr("woman") << tr("woman") << tr("woman");

            for(int i = 0; i < 5; i++)
            {
                int count = 0;
                pTableWidget->setItem(i, count++, new QTableWidgetItem(NameList[i]));
                pTableWidget->setItem(i, count++, new QTableWidgetItem(SexList.at(i))); // at在溢出时会抛出异常
                pTableWidget->setItem(i, count++, new QTableWidgetItem(QString::number(18 + i))); // int转QString
            }
        }


        //---6.7组合框
        {
            QComboBox* pComboBox = new QComboBox(this);
            pComboBox->resize(300,50);
            pComboBox->move(200,700);
            pComboBox->setFont(QFont("新宋体",12));


            //---下拉框内容添加
            pComboBox->addItem(tr("open selfdefine dialog"));
            pComboBox->addItem(tr(" >1 Zoom widget dialog"));
            pComboBox->addItem(tr(" >2 paint dialog"));
            pComboBox->setCurrentIndex(0);


            //---消息响应
            connect(pComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged),
                    this,
                    [=](int index)
            {
                mDlgTest1* pDlg1 = new mDlgTest1(this);
                pDlg1->setWindowIcon(QIcon(":/Icon/Icon.ico"));
                pDlg1->setAttribute(Qt::WA_DeleteOnClose);

                 mDlgTest2* pDlg2 = new mDlgTest2(this);
                 pDlg1->setWindowIcon(QIcon(":/Icon/Icon.ico"));
                 pDlg1->setAttribute(Qt::WA_DeleteOnClose);


                switch (index)
                {
                case 0:
                    break;

                case 1:
                    pDlg1->setWindowTitle(tr("Zoom widget dialog"));
                    pDlg1->exec();//模态对话框
                    pComboBox->setCurrentIndex(0);
                    break;

                case 2:
                    pDlg2->setWindowTitle(tr("paint dialog"));
                    pDlg2->exec();//模态对话框
                    pComboBox->setCurrentIndex(0);
                    break;
                }
            });
        }


        //---6.8文本浏览框
        m_pQTextBrowser1 = new QTextBrowser(this);
        m_pQTextBrowser1->resize(400,300);
        m_pQTextBrowser1->move(200,900);
        m_pQTextBrowser1->setFont(QFont("新宋体",12));
    }

    ConnectSigles();


}



//---8事件分发器
bool MainWindow::event(QEvent* event)
{
    if(event->type() == QEvent::MouseButtonPress)
    {
        QMouseEvent* pMouseEvent = static_cast<QMouseEvent*>(event);
        if(pMouseEvent)
        {
            QString str = QString("[x=%1,y=%2],[X=%3,Y=%4]")
                    .arg(pMouseEvent->x()).arg(pMouseEvent->y()).arg(pMouseEvent->globalX()).arg(pMouseEvent->globalY());

            ui->m_pLable1->setText(str);
            return true;
        }
    }
    return QMainWindow::event(event);
}


//---9事件过滤器
bool MainWindow::eventFilter(QObject* pObj, QEvent* pEvent)
{
    if(pObj == this->m_pLabel)
    {
        if(pEvent->type() == QEvent::MouseButtonPress)
        {
            QMouseEvent* pMouseEvent = static_cast<QMouseEvent*>(pEvent);
            if(pMouseEvent)
            {
                m_pLabel->setText(tr("trigger event filter"));
                return true;
            }
        }
    }

    return QMainWindow::eventFilter(pObj, pEvent);
}



//---信号链接函数
void MainWindow::ConnectSigles()
{
    int nWidth = 400;
    int nHight = 400;
    //---7.1创建模态对话框
    {

        connect(m_pToolButton1,&mTestButton1::clicked,
                this,
                [=]()mutable
        {
            int nReturn = QMessageBox::critical(this, tr("Notice:"), tr("click Ok open modal dialog"),QMessageBox::Ok | QMessageBox::Cancel);
            if(nReturn == QMessageBox::Ok)
            {
                QDialog* pDlg = new QDialog(this);
                pDlg->resize(nWidth, nHight);
                pDlg->setWindowIcon(QIcon(":/Icon/Icon.ico"));
                pDlg->setWindowTitle(tr("Tool dialog 1"));
                pDlg->setAttribute(Qt::WA_DeleteOnClose);
                pDlg->exec();//模态对话框
            }
        });
    }


    //---7.2创建非模态对话框
    {

        connect(m_pToolButton2, &QPushButton::clicked,
                this,
                [=]()
        {
            int nReturn =  QMessageBox::question(this, tr("Notice:"), tr("click Ok open not modal dialog"), QMessageBox::Ok|QMessageBox::Cancel);
            if(nReturn == QMessageBox::Ok)
            {
                QDialog* pDlg2 = new QDialog(this);
                pDlg2->resize(nWidth, nHight);
                pDlg2->setWindowIcon(QIcon(":/Icon/Icon.ico"));
                pDlg2->setWindowTitle(tr("tool dialog 2"));
                pDlg2->setAttribute(Qt::WA_DeleteOnClose);
                pDlg2->show();//非模态对话框
            }
        });
    }


    //---7.3打开颜色对话框
    {
        connect(m_pToolButton3, &QPushButton::clicked,
                this,
                [=]()
        {
           QColorDialog::getColor(QColor(255, 0, 0)).red();
        });
    }


    //---7.4打开文件对话框
    {
        connect(m_pToolButton4, &QPushButton::clicked,
                this,
                [=]()
        {
            QString OpenFilePath = QFileDialog::getOpenFileName(this,tr("open file"), ".","(*.txt)");
            ui->m_pLable1->setText(OpenFilePath);


            // 读取文件路径
            QFile OpenFile(OpenFilePath);
            OpenFile.open(QIODevice::ReadOnly);

            // 读取文件的两种方法
            // QByteArray array = file.readAll();
            QByteArray array;
            while(!OpenFile.atEnd())
            {
                array += OpenFile.readLine();
            }


            // 默认为utf-8
            m_pQTextBrowser1->setText(array);
            // 能读gbk文件
            // ui->textEdit->setText(codec->toUnicode(array));

            // 关闭文件
            OpenFile.close();

            OpenFile.open(QIODevice::Append);
            QString str = tr("set new value") + QString::number(qrand()%100) + "\n";
            QByteArray ba2;
            ba2.append(str);
            OpenFile.write(ba2.data());
            OpenFile.close();

        });
    }


    //---7.5保存文件对话框
    {
        connect(m_pToolButton5, &QPushButton::clicked,
                this,
                [=]()
        {
            QString SaveFilePath = QFileDialog::getSaveFileName(this,tr("save file"), ".","(*.txt)");
            ui->m_pLable1->setText(SaveFilePath);


            //---读取文件路径
            QFile SaveFile(SaveFilePath);
            if(SaveFile.open(QIODevice::WriteOnly))
            {
                for(int i = 0; i < 5; ++i)
                {
                    QString str = tr("Line")  +QString::number(i) + tr(":value = ")+ QString::number(qrand()%100) + "\n";
                    QByteArray ba2;
                    ba2.append(str);
                    SaveFile.write(ba2.data());
                }
            }

            SaveFile.close();
        });
    }


    //---7.6打开字体对话框
    {
            connect(m_pToolButton6, &QPushButton::clicked,
                    this,
                    [=]()
            {
                bool    flag;
                QFont   TempFont = QFontDialog::getFont(&flag, QFont("新宋体", 9));
            });
    }
}



MainWindow::~MainWindow()
{
    delete ui;
}



//---语言动态切换
void MainWindow::ChangeLanguageTranslation()
{
    m_pbChangeToEn = !m_pbChangeToEn;
    qApp->removeTranslator(&m_Translator);

    if(m_pbChangeToEn)
    {

        if(m_Translator.load("mTranslation_en_US.qm"))
        {

            qApp->installTranslator(&m_Translator);

            ui->retranslateUi(this);
              m_pChangeLanguageButton->setText(tr("Set Chinese"));
            qDebug()<<tr("load  English  file succed");
        }
        else
        {
            qDebug()<<tr("load  English  file error");
        }
    }
    else
    {
        if(m_Translator.load("mTranslation_zh_CN.qm"))
        {
            qApp->installTranslator(&m_Translator);
            ui->retranslateUi(this);
            m_pChangeLanguageButton->setText(tr("set English"));

            qDebug()<<tr("load  Chinese  file succed");
        }
        else
        {
            qDebug()<<tr("load  Chinese  file error");
        }
    }
}

